package com.aim.Activity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class Address extends Activity implements LocationListener{

	Context mC;
	static EditText addText, cityText, stateText, zipText,titleText, noteText, towText;

	static CheckBox bookmark;
	List<Map<String,Object>> matches = new ArrayList();
	static Resources r;
	public LocationManager myLocationManager=null;
	private String bestProvider;
	private ProgressDialog progressDialog;
	private Handler handler = new Handler(){ 
		@Override  
        public void handleMessage(Message msg) {  
			if(msg.what ==1)
			{
				progressDialog.dismiss();
				// TODO Auto-generated method stub
				SimpleAdapter	adapter1 = new SimpleAdapter(mC, matches,      
		        		R.layout.list_item_adds,      
		             new String[] { "String" },       
		        new int[] { R.id.textviewadds }); 
				
	    		AlertDialog dlg = new AlertDialog.Builder(mC)
	            .setTitle("Choose correct Address")
	            
	            .setSingleChoiceItems(adapter1, 0, new DialogInterface.OnClickListener() {

	                public void onClick(DialogInterface dialog,
	                    int pos) {
	                	
	                	if(!(matches.get(pos).get("CITY")+"").equals("null"))
	                		cityText.setText(matches.get(pos).get("CITY")+"");
	                	else
	                		cityText.setText("");
	                	
	                	
	                	if(!(matches.get(pos).get("STATE")+"").equals("null"))
	                	{
	                		String s = checkState(matches.get(pos).get("STATE")+"");
	                		stateText.setText(s);
	                	}
	                	else
	                		stateText.setText("");
	                	//lala
	                		
	                	if(!(matches.get(pos).get("ZIP")+"").equals("null"))
	                		zipText.setText(matches.get(pos).get("ZIP")+"");
	                	else
	                		zipText.setText("");
	                	
	                	dialog.dismiss();
	                }})
	            
	            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
	                public void onClick(DialogInterface dialog, int whichButton) {
	                	dialog.dismiss();
	                    /* User clicked cancel so do some stuff */
	                }
	            })
	            .create();
	            dlg.show();
			}
			if(msg.what == 2)
			{
				

					Toast.makeText(mC, "Sorry, we can't find current address",
			                Toast.LENGTH_LONG).show();
			}
		
		}
		
	};
	
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);

        mC = this;
        setContentView(R.layout.address);
        addText = (EditText) findViewById(R.id.edittextadd1);
        cityText = (EditText) findViewById(R.id.edittextcity);
        stateText = (EditText) findViewById(R.id.edittextstate); 
        zipText = (EditText) findViewById(R.id.edittextzip);
        
        
        r = getResources();
        myLocationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
	    Criteria criteria = new Criteria();
//		criteria.setAccuracy(Criteria.ACCURACY_FINE);
//        criteria.setAltitudeRequired(false);
//        criteria.setBearingRequired(false);
//        criteria.setCostAllowed(true);
//        criteria.setPowerRequirement(Criteria.POWER_LOW);
        bestProvider = myLocationManager.getBestProvider(criteria, true);
       
        
        if(ImpoundTab.impoundState != 0)
		{
		
        addText.setText(ImpoundTab.add);
        cityText.setText(ImpoundTab.city);
        stateText.setText(ImpoundTab.state);
        zipText.setText(ImpoundTab.zip);
        
		}
        
        Button buttonAdd = (Button) findViewById(R.id.buttonAdd);
        buttonAdd.setOnClickListener(new OnClickListener(){

			public void onClick(View arg0) {
				
				getAddressProgress();
				
				
			}
        	
        });

        
	}
	
	
	
	
	public void finish(){
		
		mC = null;
		addText = null;
		cityText= null;
		stateText= null;
		zipText= null;
		titleText= null;
		noteText= null;
		towText= null;
		bookmark= null;
		matches = null;
		r = null;
		myLocationManager=null;
		bestProvider = null;
		
		super.finish();
		
	}
	
	private void getAddressProgress(){
//    	flagAll = true;

        progressDialog = new ProgressDialog(mC);
        progressDialog.setButton("cancel", new DialogInterface.OnClickListener() {
        	 public void onClick(DialogInterface dialog, int i) {
//        		 flagAll = false;
        	  dialog.cancel();
        	 }
        	});
        progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
        	 public void onCancel(DialogInterface dialog) {

        	  progressDialog.dismiss();
        	  
        	 }
        	});
    	progressDialog.setCancelable(true);
    	progressDialog.setMessage("Processing, please wait!");

    	progressDialog.show();
    	
    	new Thread(){
    		  @Override  
              public void run() {  
              
    				
  				
    			  Location location = myLocationManager.getLastKnownLocation(bestProvider); 
    			      			
    			      			if (location != null)
    			      			{
    			      				Log.e("location",location.getProvider()+"   "+location.getAccuracy());
//    			      				int i = Integer.parseInt(location.getLatitude());
//    			      				double i = location.getLatitude();
//    			      				double j = location.getLongitude();
//    			      				Double lat = i*1000000;
//    			      				Double lon = j*1000000;
    			      							
    			      			}


    			      			Geocoder gc = new Geocoder(mC);
    			      			List<android.location.Address> adds = new ArrayList();

    			      			
    			      			matches.clear();
    			  				
    			      			try {

    			  					adds = gc.getFromLocation(location.getLatitude(), location.getLongitude(), 5);
    			  					
    			  				} catch (Exception e) {
    			  					// TODO Auto-generated catch block
    			  					e.printStackTrace();
    			                    handler.sendEmptyMessage(2);  

    			  				}
    			  				for (int i=0;i<adds.size();i++)
    			  				{
    			  					Map<String, Object> map = new HashMap<String, Object>();
    			  					map.put("STATE",adds.get(i).getAdminArea() );
    			  					map.put("CITY",adds.get(i).getLocality() );
    			  					map.put("ZIP",adds.get(i).getPostalCode() );
    			  					map.put("String",adds.get(i).getLocality()+","+adds.get(i).getAdminArea()+" "+adds.get(i).getPostalCode());
    			  					matches.add(map);
    			  				}
              	
              	
                  handler.sendEmptyMessage(1);  
                  
              }}.start();
    		
    	}
    	
	
	
    public static void setAddress(){
    	ImpoundTab.add= addText.getText().toString();
    	ImpoundTab.city= cityText.getText().toString();
    	ImpoundTab.state= stateText.getText().toString();
    	ImpoundTab.zip= zipText.getText().toString();
    	ImpoundTab.bookmark = bookmark.isChecked();

    }
    
    public static String checkState(String state){
    	
    	String[] states = r.getStringArray(R.array.state_array); 
    	String[] values = r.getStringArray(R.array.state_value); 
    	int i = Arrays.asList(states).indexOf(state);
    	

    	return values[i];
    }
    
	@Override
	protected void onResume() {
		super.onResume();
		myLocationManager.requestLocationUpdates(bestProvider, 1000, 0, this);
		
	}

//	@Override
//	protected void onPause() {
//		super.onPause();
//		myLocationManager.removeUpdates(this);
//	}

	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub
		
	}

	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	}
}

class MyOnItemSelectedListener implements OnItemSelectedListener {

    public void onItemSelected(AdapterView<?> parent,
        View view, int pos, long id) {

    	ImpoundTab.tow = pos+"";
    }

    public void onNothingSelected(AdapterView parent) {
      // Do nothing.
    }

}

